package main

import (
	//	"encoding/json"
	"time"
)

//保存客户端监控结果，由其他进程循环发送到服务器
var MonitorResult = make(chan []byte, 10000)

//循环执行插件
func (h *Host) Run() {
	go SendToServer()
	for {
		if len(h.Services) == 0 {
			time.Sleep(5e9)
			continue
		}
		for _, s := range h.Services {
			t := time.Now().Sub(s.LastCheck).Seconds()
			if t < float64(s.UpdateInterval) {
				continue
			}
			s.LastCheck = time.Now()
			/*
				pack := map[string]interface{}{"plugin": s.Plugin, "args": s.Args}
					go func() {
						res := Task(pack)
						MonitorResult <- res
					}()
			*/
			go func(s *Service) {
				//res := Task(pack)
				//MonitorResult <- res
				if res := RunPlugin(s); res != nil {
					MonitorResult <- res
				}
			}(s)
		}
		time.Sleep(1e9)
	}
}

//设计可能不是很好，待改进
//将采集到的监控数据发送到服务端
func SendToServer() {
	for {
		conn, err := ConnectServer(server, "8888")
		if err != nil {
			log.Error("can not connect to monitor server,wait 1 minutes to retry")
			time.Sleep(time.Minute)
			continue
		}

		for {
			res := <-MonitorResult
			log.Critical(string(res))
			err := SendData(conn, res)
			if err != nil {
				log.Error("sending monitor data to server error <%v>", err)
				MonitorResult <- res
				break
			}
			//time.Sleep(1e9)
			ReadData(conn)
			/*
			  发送完毕从服务端获取结果，如果未成功发送需要重传
			  暂时不考虑实现
			*/
		}
	}
}
